const { processMediaFile } = require("./videoProcessingUtils");

function videoProcessorBySubtitles(subtitles, validMediaFiles, startIndex, totalDuration, tempDir, concatFileContent) {
  // 计算字幕总时长
  const originalTotalDuration = subtitles.reduce((sum, subtitle) => sum + subtitle.duration, 0);
  // 如果提供了总时长并且与原始时长不同，则需要调整每张图片的显示时间
  const shouldAdjustDuration = totalDuration && Math.abs(originalTotalDuration - totalDuration) > 1;
  const durationScaleFactor = shouldAdjustDuration ? totalDuration / originalTotalDuration : 1;

  // 为每个字幕条目创建对应的视频片段
  for (let index = 0; index < subtitles.length; index++) {
    const subtitle = subtitles[index];
    let currentMedia;
    // 使用常规媒体文件（跳过首帧位置）
    currentMedia = validMediaFiles[(index + startIndex - 1) % validMediaFiles.length];
    console.log("开始处理第", index + 1, "个媒体文件：", currentMedia);
    // 使用 processMediaFile 函数处理媒体文件，避免重复代码
    const mediaFileContent = processMediaFile(currentMedia, subtitle, tempDir, index, startIndex, shouldAdjustDuration, durationScaleFactor);

    concatFileContent += mediaFileContent;
  }

  return concatFileContent;
}

module.exports = { videoProcessorBySubtitles };
